﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Http.Headers;
using Kugar.Core.Exceptions;
using Kugar.Tool.Web.RequestFieldValidation.Converters;

namespace Kugar.Tool.Web.RequestFieldValidation
{
    public static class RequestFieldServices
    {
        private static ConcurrentDictionary<Type,IRequestValueConverter> _cacheConverters=new ConcurrentDictionary<Type, IRequestValueConverter>();

        static RequestFieldServices()
        {
            _converters.Add(new DateTimeConverter());
            _converters.Add(new StringConverter());
            _converters.Add(new NumericConverter());
        }

        private static readonly List<IRequestValueConverter> _converters=new List<IRequestValueConverter>();

        /// <summary>
        /// 注册一个值转换器
        /// </summary>
        /// <param name="converter"></param>
        public static void Register(IRequestValueConverter converter)
        {
            _converters.Add(converter);

        }

        /// <summary>
        /// 转换一个string到指定类型的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="format">格式化格式,,目前只在datetime的时候使用</param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static T ConvertTo<T>(string value,string format, T defaultValue)
        {
            var converter = _cacheConverters.GetOrAdd(typeof(T), (t) =>
            {
                for (int i = 0; i < _converters.Count; i++)
                {
                    if (_converters[i].CanConvert(t))
                    {
                        return _converters[i];
                    }
                }

                return null;
            });

            if (converter==null)
            {
                throw new ArgumentTypeNotMatchException(nameof(value), typeof(T).Name);
            }

            return (T)converter.ConvertTo<T>(value, format, defaultValue);
            
        }


        #region 默认转换器

        

        #endregion

    }
}